import 'package:enterprise_v6_app/app/components/special_operation/custom_select_function.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/major_hazard/hazard_archive_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/major_hazard/hazard_archive_tree_entity.dart';

class HazardArchivesController extends GetxController {
  final tree = <HazardArchiveTreeEntity>[].obs;

  HazardArchiveTreeEntity? select;

  Future<List<HazardArchiveTreeEntity>> getArchiveTree() async {
    final resType = await HttpUtil().generateGetRequest<List<HazardArchiveTreeEntity>>(Interface.getHazardArchieveTree).execute();
    resType.onSuccess((result) {
      tree.clear();
      for (final HazardArchiveTreeEntity item in result.data ?? []) {
        tree.add(item);
        tree.addAll(item.allChildren);
      }
    });
    return resType.data ?? [];
  }

  Future<List<HazardArchiveEntity>> dataLoad(int idx, int size, {String? search}) async {
    final res = await HttpUtil().generateGetRequest<List<HazardArchiveEntity>>(
      Interface.getHazardArchievePage,
      queryParameters: {
        'pageNum': idx,
        'pageSize': size,
        'typeId': select?.id,
      },
    ).execute();
    final data = res.data ?? [];
    data.sort((a, b) => b.createDate?.compareTo(a.createDate ?? '') ?? 0);
    return data;
  }

  void showSelect() {
    CustomSelectFunction.selectMultipleBottomSheet<HazardArchiveTreeEntity>(
      onCallBack: (val) {
        select = val.first;
        update();
      },
      dataList: tree,
      checkedList: select == null ? [] : [select!],
      isMultiple: false,
    );
  }

  @override
  void onReady() {
    super.onReady();
    getArchiveTree();
  }
}
